package com.example.book.web;

import com.example.book.pojo.Book;
import com.example.book.pojo.Page;
import com.example.book.service.BookService;
import com.example.book.service.impl.BookServiceImpl;
import com.example.book.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description
 * @ClassName ClientBookSerlet
 * @Author 山山大魔王
 * @Date 2021/11/26 1:35
 * @Version 1.0
 */
@WebServlet(name = "ClientBookServlet",value = "/client/bookServlet")
public class ClientBookServlet extends BaseServlet{
    private BookService bookService = new BookServiceImpl();
    /**
     * 处理分页功能
     * @param request
     * @param response
     * @throws IOException
     */
    protected void page(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //1.获取请求参数pageNo 和pageSize
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"),1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        //2.调用BookService.page(pageNo,pageSize):page对象
        Page<Book> page = bookService.page(pageNo,pageSize);

        page.setUrl("client/bookServlet?action=page");

        //3.保存Page对象到Request域中
        request.setAttribute("page",page);
        //4.请求转发到pages/manager/book_manager.jsp页面
        request.getRequestDispatcher("/pages/client/index.jsp").forward(request,response);
    }
    /**
     * 处理区间分页功能
     * @param request
     * @param response
     * @throws IOException
     */
    protected void pageByPrice(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //1.获取请求参数pageNo 和pageSize
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"),1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        int min = WebUtils.parseInt(request.getParameter("min"),0);
        int max = WebUtils.parseInt(request.getParameter("max"),Integer.MAX_VALUE);
        //2.调用BookService.page(pageNo,pageSize):page对象
        Page<Book> page = bookService.pageByPrice(pageNo,pageSize,max,min);


        StringBuilder sb = new StringBuilder("client/bookServlet?action=pageByPrice");

        //如果有请求参数，追加到分页条的参数中
        if (request.getParameter("min")!=null){
            sb.append("&min=").append(request.getParameter("min"));
        }
        if (request.getParameter("max")!=null){
            sb.append("&max=").append(request.getParameter("max"));
        }

        page.setUrl(sb.toString());

        //3.保存Page对象到Request域中
        request.setAttribute("page",page);
        //4.请求转发到pages/manager/book_manager.jsp页面
        request.getRequestDispatcher("/pages/client/index.jsp").forward(request,response);
    }
}
